<template lang="pug">
.page
  .CustomerSalary
    .search-form.mb-10.pr-10
      Form.ivu-row.ivu-form-basic(ref="formData" :model="formData" :rules="rules" :label-width="90" v-if='hasFind')
        FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
          template(v-if="item.type === 'select'")
            Select(v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
              Option(
                v-for="(c_item, index) in arrListDown[item.options]"
                :value="c_item.value"
                :key="index"
              ) {{ c_item.text }}
          template(v-if="item.type === 'input'")
            Input(v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
          template(v-if="item.type === 'datePicker'")
            DatePicker.w-100(:value="formData[item.model]" :placeholder="item.placeholder" type="year" @on-change="handleChangeDatePicker(item.model, $event)")
          template(v-if="item.type === 'cascader'")
            .areaTree
              Cascader(v-model="formData[item.model]" :data="areaTree" clearable change-on-select @on-change="areaTreeChange(item.model, $event)")
          template(v-if="item.type === 'button'")
            Button(type="info" @click="searchFn") 查询

    .pl-20.pr-20.bg-white
      Table.hasTitle-table.beautiful-table(:columns="thead" :data="tableData" :stripe="true"
        @on-selection-change="tableSelectChange"
      )
        .clearfix.font-16(slot="header")
          .table-title-lefttxt.pull-left
            |合计
            span.text-info.pl-5.pr-5.font-weight {{tableComone.totalRows}}
            |条
          .pull-right.table-title-btns
            Button.mr-10(v-if="hasSaveBasicsType" type="info" @click="handleShowCreateTreatmentParamTypeModal('')") 新增
            Button.mr-10(v-if="hasImport" type="info" @click="handleShowTreatmentParamManageModal") 导入
            Button.mr-10(v-if="hasExport" type="info" @click="exportBtn") 导出
            Button.mr-10(v-if="hasDelete" type="warning" @click="handleDelete(selectedIdArr.join(','))" :disabled="!selectedIdArr.length > 0") 删除

        template(slot-scope="{ row, index }" slot="action")
          Button( v-if="hasView" type="text" size="small" @click="handleShowCreateTreatmentParamTypeModal(row.id)") 编辑
          Button( v-if="hasTreatmentAnnexManage" type="text" size="small" @click="goTreatmentParamManageDetail(row.id, row.whetherDifferentiateCities)") 附件管理
          Button( v-if="hasUpdate" type="text" size="small" @click="changeStatus(row)") {{row.status == 1 ? '启用' : '禁用'}}
          Button( v-if="hasDelete" type="text" size="small" @click="handleDelete(row.id)") 删除
          

        .clearfix.pl-20.pr-20(slot="footer")
          Page(
            :current="tableComone.pageIndex"
            :total="tableComone.totalRows"
            @on-change="onChangePage"
            @on-page-size-change="onpageSizeChange"
            show-sizer
            show-total
            placement="top"
            prev-text="上一页"
            next-text="下一页"
            :page-size-opts="[10, 20, 30, 50, 100]"
          )
    TreatmentParamManage(ref="TreatmentParamManageModal" @handleMaxSizeTen="handleMaxSizeTen" @query="searchFn")
    //- 新建弹窗
    CreateTreatmentParamTypeModal(ref="CreateTreatmentParamTypeModal" @handleSave="searchFn")
</template>

<script>
import { Common } from '@/utils/common.js'
import { SysInitCustomerSalaryApi } from '@/api/SysInitCustomerSalary.api.js'
import { TreatmentBasicsTypeApi } from '@/api/TreatmentBasicsType.api.js'
import { basicThead } from './CStableHead.js'
import _cloneDeep from 'clone-deep'
// import CustomerSalaryImportModal from './modal/CustomerSalaryImportModal.vue'
import TreatmentParamManage from './modal/treatmentParamManageModal.vue'
import { ProvinceList, AreaTree } from '@/utils/publicJson.js'
import CreateTreatmentParamTypeModal from './modal/CreateTreatmentParamTypeModal.vue'
import { constants } from 'fs';
export default {
  name: 'treatmentParamManage',

  components: {
    // CustomerSalaryImportModal,
    TreatmentParamManage,
    CreateTreatmentParamTypeModal
  },

  data () {
    return {
      thead: _cloneDeep(basicThead),
      tableData: [],
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10 // 当前页面展示条数
      },
      formData: {
        name: '',
        month: new Date(),
        parameterType: '00000000-0000-0000-0000-000000000000',
        cooperateType: '',
        cityId: [],
        serverId: ''
      },
      formItem: [
        { type: 'select', label: '参保险种：', placeholder: '请选择参保险种', prop: 'parameterType', model: 'parameterType', options: 'parametertype', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-9 ivu-col-span-xxl-6' },
        { type: 'input', label: '待遇名称：', placeholder: '请输入待遇名称', prop: 'treatmentName', model: 'treatmentName', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-8' },
        { type: 'button', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-4' }
      ],
      rules: {},
      arrListDown: {
        parametertype: [],
        parameterstatus: []
      },
      selectedId: '', // 勾选的id集合
      selectedIdArr: [], // 勾选的id, name数组集合
      axsEnableSwitch: false,
      areaTree: [] // 中国所有城市树
    }
  },
  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 附件管理
    hasTreatmentAnnexManage () {
      return this.actionArr.indexOf('TreatmentAnnexManage') > -1
    },
    // 获取待遇享受参保险种列表
    hasGetInsuranceTypeList () {
      return this.actionArr.indexOf('GetInsuranceTypeList') > -1
    },
    hasUpdate () {
      return this.actionArr.indexOf('Update') > -1
    },
    // 新增
    hasSaveBasicsType  () {
      return this.actionArr.indexOf('SaveBasicsType') > -1
    },
    // 查询
    hasFind () {
      return this.actionArr.indexOf('Find') > -1
    },
    // 编辑
    hasView () {
      return this.actionArr.indexOf('View') > -1
    },
    // 删除
    hasDelete () {
      return this.actionArr.indexOf('Delete') > -1
    },
    // 上传附件
    hasTreatmentAnnexUpload () {
      return this.actionArr.indexOf('TreatmentAnnexUpload') > -1
    },
    hasGetBasicsTypeAnnexList () {
      return this.actionArr.indexOf('GetBasicsTypeAnnexList') > -1
    },
    
    // 导入
    hasImport () {
      return this.actionArr.indexOf('Import') > -1
    },
    // 导出
    hasExport () {
      return this.actionArr.indexOf('Export') > -1
    }
  },

  watch: {
  },

  mounted () {
    this.getInsuranceTypeList()
    this.query()
  },

  methods: {
    // 删除
    async handleDelete (id) {
      this.$Modal.confirm({
        title: '是否确认删除该条信息',
        onOk: async () => {
          let res = await TreatmentBasicsTypeApi.delete({
            id: id
          })
          if (res.data.success) {
            this.$Message.success(res.data.message)
            this.selectedIdArr = []
            this.query()
          } else {
            this.$Message.error({
              content: res.data.message,
              duration: 10,
              closable: true
            })
          }
        }
      })
      
    },

    // 获取参保险种页面数据源
    async getInsuranceTypeList () {
      let res = await TreatmentBasicsTypeApi.getInsuranceTypeList()
      console.log('获取参保险种页面数据源res: ', res)
      if (res.status === 200 && res.data.success) {
        var result = res.data.data
        this.arrListDown.parametertype = result
      }
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageSize = val
      this.query()
    },
    // 启用/禁用
    changeStatus (row) {
      console.log(row,'row')
      var params = {
        Id: row.id.toUpperCase(),
        Status: row.status == 0 ? 1 : 0
      }
      TreatmentBasicsTypeApi.updateTypeStatus(params).then(res => {
        console.log('保存待遇参数: ', res)
        if (res.status === 200 && res.data.success) {
          this.$Message.success(res.data.message)
          this.query()
        } else {
          this.isCanSubmit = true
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    },
    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      console.log('query')
      var params = {
        InsuredTypeId: this.formData.parameterType,
        TreatmentName: this.formData.treatmentName,
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize
      }
      let res = await TreatmentBasicsTypeApi.getList(params)
      console.log('客户薪资res: ', res)
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data
        this.tableComone.totalRows = res.data.totalRows
        this.axsEnableSwitch = res.data.axsEnableSwitch

        this.selectedIdArr = []
        this.selectedId = ''
      } else {
        this.tableData = []
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
      this.loading = false
    },

    // 搜索
    searchFn () {
      this.tableComone.pageIndex = 1
      this.query()
    },

    goTreatmentParamManageDetail (id, whetherDifferentiateCities) {
      this.$router.push({
        path: '/treatmentParamTypeDetail',
        name: 'treatmentParamTypeDetail',
        query: {
          id: id,
          whetherDifferentiateCities: whetherDifferentiateCities
        }
      })
    },

    // table选择
    tableSelectChange (value) {
      console.log(value)
      this.selectedIdArr = value.map((item) => {
        return item.id
      })
    },

    // 导入薪资弹窗
    handleShowCustomerSalaryImportModal () {
      this.$refs.CustomerSalaryImportModal.show() // 显示弹窗
      this.$refs.CustomerSalaryImportModal.errorData.isError = false // 隐藏错误数据下载按钮
      this.$refs.CustomerSalaryImportModal.isCanUpload = true // 可导入按钮
      this.$refs.CustomerSalaryImportModal.salaryStartTimeDefault = new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1), // 上个月1号
      this.$refs.CustomerSalaryImportModal.salaryEndTimeDefault = new Date(new Date().getFullYear(), new Date().getMonth() - 1, 30), // 上个月30号
      this.$refs.CustomerSalaryImportModal.handleClearFiles()
    },

    // 批量导入-显示弹窗
    handleShowTreatmentParamManageModal () {
      this.$refs.TreatmentParamManageModal.show()
      this.$refs.TreatmentParamManageModal.file = null
      this.$refs.TreatmentParamManageModal.errorData.isError = false
      // this.$refs.TreatmentParamManageModal.year = this.$moment(this.tableData[0].salaryMonth).format('YYYY')
    },

    // 显示新增弹窗
    handleShowCreateTreatmentParamTypeModal (id) {
      this.$refs.CreateTreatmentParamTypeModal.id = id
      // this.$refs.CreateTreatmentParamTypeModal.isShowCreateTreatmentParamTypeModal = true
      this.$refs.CreateTreatmentParamTypeModal.isCreate = id ? false : true 
      this.$refs.CreateTreatmentParamTypeModal.show()
      this.$refs.CreateTreatmentParamTypeModal.arrListDown = this.arrListDown
      if (id) {
        this.$refs.CreateTreatmentParamTypeModal.getModel(id)
        this.$refs.CreateTreatmentParamTypeModal.formItem[0].isDisabled = true
        this.$refs.CreateTreatmentParamTypeModal.formItem[1].isDisabled = true
      } else {
        this.$refs.CreateTreatmentParamTypeModal.formItem[0].isDisabled = false
        this.$refs.CreateTreatmentParamTypeModal.formItem[1].isDisabled = false
      }
      // Object.keys(this.$refs.CreateTreatmentParamTypeModal.formCreate).forEach(key => {
      //   console.log('key',key)
      //   if (key === 'enabled') {
      //     this.$refs.CreateTreatmentParamTypeModal.formCreate[key] = true
      //   } else {
      //     this.$refs.CreateTreatmentParamTypeModal.formCreate[key] = ''
      //   }
      // })
    },

    // 时间控件
    handleChangeDatePicker (model, value) {
      this.formData[model] = value
    },

    // 所在地区选择
    areaTreeChange (model, value) {
      this.formData[model] = value
    },

    handleMaxSizeTen () {
      this.$Message.error({
        content: '您上传的文件太大，上传文件大小不能超过50M',
        duration: 50,
        closable: true
      })
    },
    // 导出按钮
    exportBtn () {
      TreatmentBasicsTypeApi.export({
        IdList: this.selectedIdArr.join(','),
        InsuredTypeId: this.formData.parameterType,
        TreatmentName: this.formData.treatmentName,
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize
      }).then(res => {
        console.log(res)
        if (res.data.success) {
          let objectUrl = '/' + res.data.data.replace(/\\/g, '\/')
          const link = document.createElement('a')
          link.download = ''
          link.href = objectUrl
          link.click()
        } else {
          this.$Message.error({
            content: res.data.message,
            duration: 10,
            closable: true
          })
        }
      })
    }
  }
}
</script>

<style lang="less" scope>
</style>
